<?php
class Default_Model_CatalogueMenu extends Zend_Db_Table
{
	protected $_name = 'catalogue';
	protected $_primary = 'id';
	
	public function __construct($parent)
	{
		$this->_parent = $parent;
	}
	
	// get catalogue to create menu
	public function getMenu()
	{
		$db = Zend_Registry::get('connectDb');
		$select = $db->select()
				->from('catalogue', array('id', 'title'))
				->where('status = 1')
				->where('parent = ?', $this->_parent, INTEGER);
		// only show catalogues contain data
		if ($this->_parent == 0) {
			$select->where("(`id` IN (SELECT `cat` FROM `article` WHERE `status` = 1)
				       OR `id` IN (SELECT `parent` FROM `catalogue` WHERE `id` IN (SELECT `cat` FROM `article` WHERE `status` = 1)))");
		}
		else {
			$select->where("id IN (SELECT `cat` FROM `article` WHERE `status` = 1)");
		}
		$select->order('order', 'ASC');
		return $db->fetchAll($select);
	}
	
	public function isParent($cid)
	{
		$db = Zend_Registry::get('connectDb');
		$select = $db->select()
				->from('catalogue', array('id'))
				->where('parent = ?', $cid, INTEGER)
				->limit(1);
		$result = $db->fetchRow($select);
		return ( ! empty($result)) ? true : false;
	}
}